package com.lwc.backendsinglestructure.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.lwc.backendsinglestructure.common.BaseResponse;
import com.lwc.backendsinglestructure.common.utils.ResultUtils;
import com.lwc.backendsinglestructure.domain.dto.user.LoginForm;
import com.lwc.backendsinglestructure.domain.entity.User;
import com.lwc.backendsinglestructure.domain.vo.wx.AuthorResult;
import com.lwc.backendsinglestructure.domain.vo.wx.UserResult;
import com.lwc.backendsinglestructure.domain.vo.wx.WeixinQrCode;
import com.lwc.backendsinglestructure.mapper.UserMapper;
import com.lwc.backendsinglestructure.service.UserService;
import com.lwc.backendsinglestructure.service.WxService;
import com.lwc.backendsinglestructure.utils.cache.CacheUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.mybatisflex.core.query.QueryWrapper;
/**
 * 微信服务器回调接口
 */
@Slf4j
@RestController
public class WxServerController {

    @Autowired
    private WxService wxService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private UserService userService;
    @Autowired
    UserMapper userMapper;
    /**
     * 配置回调接口时微信公众号验签接口
     * @param request
     * @return
     */
    @GetMapping(value = "/weixin/check")
    public String weixinCheck(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        if (StrUtil.isEmpty(signature) || StrUtil.isEmpty(timestamp) || StrUtil.isEmpty(nonce)) {
            return "";
        }
        wxService.checkSignature(signature, timestamp, nonce);
        return echostr;
    }

    /**
     * 扫码回调
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    @PostMapping(value = "/weixin/check")
    public String weixinMsg(@RequestBody String requestBody, @RequestParam("signature") String signature,
                            @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {

        log.debug("requestBody:{}", requestBody);
        log.debug("signature:{}", signature);
        log.debug("timestamp:{}", timestamp);
        log.debug("nonce:{}", nonce);

        wxService.checkSignature(signature, timestamp, nonce);
        return wxService.handleWeixinMsg(requestBody);
    }



    /**
     * 获取带参二维码
     * @return
     */
    @GetMapping(value = "/wx/user/qrcode")
    public BaseResponse<WeixinQrCode> getQrCode() {
        WeixinQrCode qrCode = wxService.getQrCode();
        qrCode.setUrl(null);
        qrCode.setExpireSeconds(null);
        return ResultUtils.success(qrCode);
    }

    /**
     * 校验是否扫描完成
     * 完成，返回 JWT
     * 未完成，返回 check faild
     *
     * @param ticket
     * @return
     */
    @GetMapping(value = "/wx/user/login/qrcode")
    public BaseResponse<?> userLogin(String ticket) {
        // key：ticket -- value：openid
        String openId = cacheUtil.get(ticket);
        if (StrUtil.isNotEmpty(openId)) {
            // 通过openid 到数据库中查询有没有 有的话就返回登录信息
            LoginForm loginForm = new LoginForm();
            loginForm.setType("wx");
            loginForm.setOpenId(openId);
            User user = userService.login(loginForm);
            if(user != null){
                return ResultUtils.success(user);
            }
        }
        return ResultUtils.error(null);
    }


    /**
     * 网页授权获取用户信息  用户同意授权 , 获取code
     *
     * @return
     */
    @GetMapping(value = "getUserInfo")
    public void getUserInfo(String code,String ticket) {
        // 拿code再去调用第三方接口
        String api = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxec69271754a6bd7d&secret=b73e34a25e1679f8997bd454d8b81071&code="+ code +"&grant_type=authorization_code";
        String result = HttpUtil.get(api);
        AuthorResult authorResult = JSONUtil.toBean(result, AuthorResult.class);
        String api2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+ authorResult.getAccess_token() +"&openid="+ authorResult.getOpenid() +"&lang=zh_CN";
        String result2 = HttpUtil.get(api2);
        UserResult userResult = JSONUtil.toBean(result2, UserResult.class);
        // 通过openid 查询数据库 没有就自动注册
        if(!userResult.getOpenid().isBlank()){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq(User::getOpenId, userResult.getOpenid());
            User user = userMapper.selectOneByQuery(queryWrapper);
            if(user == null){
                user = new User();
                user.setOpenId(userResult.getOpenid());
                user.setUsername("rel12121"); // 需要随机区分一下
                user.setNickName(userResult.getNickname());
                user.setSex(1);
                user.setRole("普通用户");
                user.setStatus(1);
                userMapper.insert(user);
            }
        }

    }
}
